import axios from 'axios'
import { Modal, message } from 'ant-design-vue'
import ls from '@/utils/Storage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { clearUserInfo } from '@/utils/util'
const shotOffCodes = ['100001', '100005', '100007', '100011']
const service = axios.create({
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})
let shotOffDialog
// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = ls.get(ACCESS_TOKEN)
    if (token) {
      // 如果由本地管理，则需要在头文件增加token
      config.headers[import.meta.env.VITE_TOKEN_KEY] = token
    }
    if (config.options && config.options.timeout) {
      config.timeout = config.options.timeout
    }

    return config
  },
  (error) => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data
    const action = response.headers[import.meta.env.VITE_ACTION_KEY || 'action']
    if (action === 'create') {
      ls.set(ACCESS_TOKEN, response.headers[import.meta.env.VITE_TOKEN_KEY])
    }
    if (action === 'update') {
      ls.set(ACCESS_TOKEN, response.headers[import.meta.env.VITE_TOKEN_KEY])
    }
    if (action === 'delete') {
      ls.remove(ACCESS_TOKEN)
    }
    if (response.config.options && response.config.options.responseCheck == false) {
      return res
    }
    // 文件上传接口下载
    if(res.code === undefined && res.msg === undefined) {
      return res;
    }
    if (res.code !== '000000') {
      if (shotOffCodes.filter((value) => res.code === value).length > 0) {
        if (!shotOffDialog) {
          // to re-login
          shotOffDialog = Modal.error({
            title: '提示',
            content: res.msg,
            okText: '确认',
            closable: false,
            onOk() {
              clearUserInfo()
              location.href = '/'
            }
          })
        }
      } else {
        if (response.config.options && response.config.options.notice == false) {
        } else {
          message.info(res.msg || import.meta.env.VITE_DEFAULT_MESSAGE)
        }
      }
      return Promise.reject(new Error(res.msg || import.meta.env.VITE_DEFAULT_MESSAGE))
    } else {
      return res
    }
  },
  (error) => {
    message.info({ content: '网络连接错误，请重试!', key: 'network' })
    return Promise.reject(error)
  }
)

export default service
